<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>利用原型的特性实现一个观察者模式，代码如下</title>
</head>
<body>
<script>
    function Observer(){
        this.fns=[];
    }
    Observer.prototype={
        subscribe:function(fn){
            this.fns.push(fn);
        },
        unsubscribe:function(fn){
            this.fns=this.fns.filter(
                function(el){
                    if(el!==fn){
                        return el;
                    }
                }
            );
        },
        update:function(o,thisObj){
            var scope=thisObj || window;
            this.fns.forEach(
                function(el){
                    el.call(scope,o);
                }
            );
        }
    };
    //测试
    var o=new Observer;
    var f1=function(data){
        console.log('Robin:'+data+',赶紧干活了！');
    };
    var f2=function(data){
        console.log('Randal1:'+data+',找他加工资去');
    };
    o.subscribe(f1);
    o.subscribe(f2);
    o.update("Tom回来了")
    //退订f1
    o.unsubscribe(f1);
    //再来验证
    o.update('Tom回来了!');
</script>
</body>
</html>